/**
 * Created by huotaol on 2017/5/9.
 */
import React, {Component} from "react";
import {
    Alert,
    Image,
    ScrollView,
    StyleSheet,
    Text,
    TextInput,
    TouchableHighlight,
    TouchableOpacity,
    View
} from "react-native";
import CustomStyle from "../../../common/style/CustomStyle";
import {connect} from "react-redux";
import Util from "../../main/Util";
import {Actions} from "react-native-router-flux";
import Toast from "react-native-root-toast";
import * as MineAction from "../../redux/action/Mine";

const BACKGROUND = require('../../../img/login/bacground.png');

class LoginUI extends Component {

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            phone: '',
            password: '',
        };
    }

    render() {
        return (
            <View style={{flex: 1}}>
                <Image
                    resizeMode={'cover'}
                    source={BACKGROUND}
                    style={{
                        width: CustomStyle.screenWidth,
                        height: CustomStyle.getActualSizeInVertical(530),
                    }}/>

                <ScrollView>
                    <View style={{
                        paddingLeft: CustomStyle.getActualSizeInHorizontal(20),
                        paddingRight: CustomStyle.getActualSizeInHorizontal(20),
                    }}>
                        <View style={[styles.inputContainer, {marginTop: CustomStyle.getActualSizeInVertical(80),}]}>
                            <TextInput style={[CustomStyle.baseText, {flex: 1}]} placeholder={'请输入手机号'}
                                       keyboardType='numeric'
                                       maxLength={11}
                                       underlineColorAndroid={'#00000000'}
                                       onChangeText={(value) => {
                                           this.setState({phone: value});
                                       }}
                            />
                        </View>
                        <View style={[styles.inputContainer, {marginTop: CustomStyle.getActualSizeInVertical(40),}]}>
                            <TextInput style={[CustomStyle.baseText, {flex: 1}]} placeholder={'请输入密码'}
                                       secureTextEntry={true}
                                       underlineColorAndroid={'#00000000'}
                                       onChangeText={(value) => {
                                           this.setState({password: value});
                                       }}
                            />
                        </View>

                        <TouchableHighlight
                            onPress={() => {
                                this._login();
                            }}
                            underlayColor='#fabc00'
                            style={[styles.btContainer, {
                                backgroundColor: '#ffc000',
                                marginTop: CustomStyle.getActualSizeInVertical(80),
                            }]}>
                            <View >
                                <Text style={[CustomStyle.baseText, styles.btText,]}>登录</Text>
                            </View>
                        </TouchableHighlight>
                        <TouchableHighlight
                            style={[styles.btContainer, {
                                backgroundColor: '#ff7200',
                                marginTop: CustomStyle.getActualSizeInVertical(30),
                            }]}
                            underlayColor='#ef6500'
                            onPress={() => {
                                Actions.Register({name: 'Register'});
                            }}
                        >
                            <View >
                                <Text style={[CustomStyle.baseText, styles.btText,]}>注册</Text>
                            </View>
                        </TouchableHighlight>
                    </View>
                </ScrollView>

                <TouchableOpacity
                    style={[, {alignSelf: 'center', marginBottom: CustomStyle.getActualSizeInVertical(40),}]}
                    onPress={() => {
                        Actions.Password({name: 'Password', phoneNumber: this.state.phone});
                    }}
                >
                    <Text
                        style={[CustomStyle.baseText, {
                            fontSize: CustomStyle.getActualFontSize(24),
                            color: '#ff7200',
                        }]}>忘记密码？点这里</Text>
                </TouchableOpacity>

                <TouchableOpacity
                    style={[, {
                        position: 'absolute',
                        left: CustomStyle.getActualSizeInHorizontal(30),
                        top: CustomStyle.getActualSizeInVertical(CustomStyle.navBasePaddingTop + 30),
                        width: CustomStyle.getActualSizeInHorizontal(48),
                        height: CustomStyle.getActualSizeInVertical(48),
                    }]}
                    onPress={() => {
                        Actions.pop();
                    }}
                >
                    <Image source={require('../../../img/header_back.png')} style={{
                        width: CustomStyle.getActualSizeInHorizontal(18),
                        height: CustomStyle.getActualSizeInVertical(32),
                    }}/>
                </TouchableOpacity>

            </View>
        );
    }

    _login() {
        if (this.state.phone && this.state.password) {
            const params = {
                phone: this.state.phone,
                password: this.state.password,
                userid: null,
                token: null,
            };
            Util.postServer('user/login', params, (result) => this._onLoginSuccess(result), (msg) => this._onLoginFailed(msg));
        } else {
            Alert.alert("错误", "请输入完整信息");
        }
    }

    _onLoginSuccess(result) {
        if (result.status === '0') {
            Toast.show("登录成功", {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
            const param = {
                id: result.data.user.userid,
                token: result.data.user.token,
                phone: result.data.user.phone,
                info: result.data.user,
            };
            this.props.updateUser(param);
            Util.storage.save({
                key: 'users',
                id: '1000',
                rawData: param,
                expires: null
            });
            Actions.pop({refresh: {}});
        }
        else {
            Alert.alert('错误:', result.msg);
        }
    }

    _onLoginFailed(msg) {
        Toast.show(msg, {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
    }

}

export const styles = StyleSheet.create({
    inputContainer: {
        height: CustomStyle.getActualSizeInVertical(88),
        justifyContent: 'center',
        backgroundColor: "#fffcee",
        borderRadius: CustomStyle.getActualSizeInHorizontal(4),
        paddingLeft: CustomStyle.getActualSizeInHorizontal(20),
        paddingRight: CustomStyle.getActualSizeInHorizontal(20),
    },
    inputText: {
        color: '#82a682',
        fontSize: CustomStyle.getActualFontSize(30),
    },

    btContainer: {
        borderRadius: CustomStyle.getActualSizeInHorizontal(44),
        height: CustomStyle.getActualSizeInVertical(88),
        alignItems: 'center',
        justifyContent: 'center',
    },
    btText: {
        color: '#ffffff',
        fontSize: CustomStyle.getActualFontSize(30),
    },
});

const mapStateToProps = (state) => {
    const {userData} = state;
    return {
        userData: userData,
    };
};

const mapDispatchToProps = (dispatch) => {
    return {
        updateUser: param => dispatch(MineAction.userData(param)),
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(LoginUI);